package com.manulife.hk.performance.converter;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Optional;

@Converter(autoApply = true)
public class OffsetDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
	@SuppressWarnings("static-access")
	@Override
	public Timestamp convertToDatabaseColumn(LocalDateTime localDateTime) {
		// add System Zone
		ZonedDateTime zonedDateTime = localDateTime.atZone((ZoneId.systemDefault()));
		// transform to UTC Zone Datetime
		zonedDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of("Z"));
		LocalDateTime utcDateTime = zonedDateTime.toLocalDateTime();
		// transform to DBtype
		Timestamp timestamp = Optional.ofNullable(utcDateTime).map(Timestamp::valueOf).orElse(null);
		return timestamp;
	}

	@Override
	public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
		// UTC DateTime
		LocalDateTime utcDateTime = Optional.ofNullable(timestamp).map(Timestamp::toLocalDateTime).orElse(null);
		// Utc Zone Datetime
		ZonedDateTime zoneDateTime = utcDateTime.atZone((ZoneId.of("Z")));
		// Transform to System Zone DateTime
		zoneDateTime = zoneDateTime.withZoneSameInstant(ZoneId.systemDefault());
		// System Datetime
		LocalDateTime localDateTime = zoneDateTime.toLocalDateTime();
		return localDateTime;
	}
}